from flask import Flask, render_template, jsonify, request

from flask_sqlalchemy import SQLAlchemy

from datetime import datetime

import logging

app = Flask(__name__)
app.config["SQLALCHEMY_DATABASE_URI"] = "mysql+pymysql://root:123456@localhost/db_web"
app.config["SQLALCHEMY_TRACK_MODIFICATIONS"] = False

logging.basicConfig()
logging.getLogger('sqlalchemy.engine').setLevel(logging.INFO)
app.config['SQLALCHEMY_ECHO'] = True  # 直接输出SQL到控制台



db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80))
    email = db.Column(db.String(120))
    create_time = db.Column(db.DateTime, default=datetime.now)

@app.route("/")
def home():
    users = User.query.all()
    return render_template('index.html', title='Home', now=datetime.now().strftime("%Y-%m-%d %H:%M")
                           , users=users)

@app.get("/user")
def getUsers():
    try:
        # 获取分页参数，默认为第1页，每页10条
        page = request.args.get('page', 1, type=int)
        per_page = request.args.get('per_page', 10, type=int)
        
        # 按创建时间降序分页查询
        pagination = User.query.order_by(User.create_time.desc()).paginate(
            page=page, 
            per_page=per_page,
            error_out=False
        )
        
        # 构建返回数据
        users = pagination.items
        return jsonify({
            "users": [{
                "id": user.id,
                "name": user.name,
                "email": user.email,
                "create_time": user.create_time.isoformat() if user.create_time else None
            } for user in users],
            "pagination": {
                "total": pagination.total,
                "pages": pagination.pages,
                "current_page": pagination.page,
                "per_page": pagination.per_page,
                "has_next": pagination.has_next,
                "has_prev": pagination.has_prev
            }
        })
    except Exception as e:
        return jsonify({"error": str(e)}), 500

@app.post("/user")
def createUser():
    # 从请求体中获取表单数据
    name = request.form.get("name")
    email = request.form.get("email") 
    # 参数校验
    if not name or not email:
        return jsonify({"error": "姓名和邮箱不能为空"}), 400
   
    user = User(name=name, email=email)
    db.session.add(user)
    db.session.commit()
    return jsonify({"message": "已成功添加"})

if __name__ == "__main__":
    with app.app_context():
        db.create_all()
    app.run(debug=True)
    
